#!/usr/bin/env python
import sys
import re
import os
sohead = re.compile('(.+\.so):')
funchead = re.compile('([0-9a-f]{8}) <(.+)>:')
funcline = re.compile('^[ ]+([0-9a-f]+):.+')

############################################################
def getshortPC(longPC):
    #print longPC
    i=0
    while True:
        temp=longPC[i]
        if temp!='0':
            pc = longPC[i:]
            break
        if i >= len(longPC):
            break
        i=i+1
    #print pc
    return pc
    
def parsesnative_crash_pc(lines):
    #print 'parsesnative'
    #crashline = re.compile('.+pc.([0-9a-f]{8}).+%s' % filename )
    crashline = re.compile('.+(#.+pc.[0-9a-f]{8}.+)')
    ret = []
    for l in lines:
        m = crashline.match(l)
        if m:
            addr =  m.groups()[0]
            ret.append(addr)
    return ret

    
def parsesnative_get_code_from_pc(lines,pc):
    crashline=re.compile('^[ ]+([0-9a-f]+:.+)')
    funchead = re.compile('([^ ]{5,})')
    func = []
    for l in lines:
        m = crashline.match(l)
        if m:
            code =  m.groups()[0]
            if  pc in code :
                print code
                break
        else:
            func.append(l)
            
        m = funchead.match(l)
        if m:
           func=[]
           func.append(l)
           
    print func
    return   func
#############################################################

def parseasm( lines ):
    ret = []
    current = None
    restartcode = False;
    print 'parseasm'
    for l in lines:
        m = funchead.match(l)
        if m:
            if current:
                ret.append(current)
            print m.groups();
            startaddr, funcname =  m.groups()
            current = [ funcname, int(startaddr,16), int(startaddr,16), int(startaddr,16), [] ]
            continue
        m = funcline.match(l)
        if m:
            restartcode = True;
            addr =  m.groups()[0]
            if current != None:
                current[3] = int(addr,16)
            continue
        m = sohead.match(l)
        if m:
            so =  m.groups()[0]
            so = os.path.split(so)[1]
            continue
        #Assume anything else is a code line
        if restartcode:
#            print 'XXX',l
            restartcode = False;
            ret.append(current)
            current = [ current[0], current[1], current[3], current[3], [] ] 
        if current != None:
            current[4].append(l);
    print ret
if __name__=="__main__":
    #asm, stack = sys.argv[1],sys.argv[2]
    print 'main'
    parseasm( file('getver.asm').read().split('\n') )
    #print libname + asm
    """
    stack = parsestack( file('./log').read().split('\n'), 'libc.so' )
    print stack
    
    for addr in stack:
        for func, funcstart, segstart, segend, code in asm:
            if addr >= segstart and addr <= segend:
                print "0x%08x:%32s + 0x%04x %s" % ( addr, func, addr-funcstart, "".join(["\n"+x for x in code]))
    """

